import React, { useCallback, useEffect, useRef, useState } from 'react'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { Button, Modal, Form, Input, Upload, message } from 'antd'
import { RcFile, UploadChangeParam, UploadFile, UploadProps } from 'antd/lib/upload'
import projectApi, { formDataModel } from '@/api/project'
export default function ModalTrade(props: any) {
  const [form] = Form.useForm()
  const { isModalOpen, modalIsShow, reqTrademarkList, trademark } = props
  const [loading, setLoading] = useState(false)
  // 品牌名称
  const [tmName, setTmName] = useState('')
  // 图片地址
  const [logoUrl, setLogoUrl] = useState<string>('')
  const [id, setId] = useState<undefined | number>(undefined)
  // 上传前
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('只能上传Jpg图片')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('最大为2m')
    }
    return isJpgOrPng && isLt2M
  }
  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e
    }
    return e && e.fileList
  }
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    setLogoUrl(info.file.response.data)
    setLoading(false)
  }
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传LOGO</div>
    </div>
  )
  const saveTrademark = async () => {
    try {
      await form.validateFields()
      await projectApi.AETrademark(formData())
      message.success('保存成功')
      modalIsShow(false)
    } catch (error) {
      message.error(error)
    } finally {
      reqTrademarkList()
    }
  }
  const cloneModal = () => {
    setLogoUrl('')
    setTmName('')
  }
  useEffect(() => {
    setTmName(trademark.tmName)
    setLogoUrl(trademark.logoUrl)
    setId(trademark.id)
    form.setFieldsValue({ tmName: trademark.tmName })
  }, [trademark])
  const formData = useCallback((): formDataModel => {
    if (id) {
      return {
        id,
        tmName,
        logoUrl
      }
    } else {
      return {
        tmName,
        logoUrl
      }
    }
  }, [tmName, logoUrl, id])
  return (
    <>
      <Modal
        width="50%"
        title={id ? '编辑名称' : '添加品牌'}
        onCancel={() => modalIsShow(false)}
        onOk={saveTrademark}
        open={isModalOpen}
        afterClose={cloneModal}
        destroyOnClose={true}
        forceRender={true}
      >
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ tmName: tmName }}
          autoComplete="off"
        >
          <Form.Item
            label="品牌名称"
            validateTrigger={['onBlur']}
            name="tmName"
            rules={[
              {
                validator(rule, value) {
                  if (!value) {
                    return Promise.reject('品牌名称不能为空')
                  }
                  if (value.length < 5) {
                    return Promise.reject('品牌名称不能少于5个字')
                  }
                  return Promise.resolve()
                }
              }
            ]}
          >
            <Input value={tmName} onInput={(e) => setTmName((e.target as any).value)} />
          </Form.Item>
          <Form.Item
            label="品牌LOGO"
            name="file"
            valuePropName="fileList"
            getValueFromEvent={normFile}
            rules={[
              {
                validator(rule, value) {
                  if (!logoUrl) {
                    return Promise.reject('请上传文件')
                  }
                  return Promise.resolve()
                }
              }
            ]}
          >
            <Upload
              name="file"
              listType="picture-card"
              showUploadList={false}
              action="http://101.43.227.123:5555/app-prod/admin/product/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {logoUrl ? <img src={logoUrl} alt="file" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
